package com.sangmo.fts.process.inventory.service;

import com.sangmo.boot.framework.common.errors.ServiceException;
import com.sangmo.boot.framework.common.errors.StandardErrors;
import com.sangmo.boot.framework.common.utils.DateUtils;
import com.sangmo.boot.framework.data.idm.IdentityManager;
import com.sangmo.boot.framework.plugin.dataview.crud.service.BaseViewService;
import com.sangmo.boot.framework.plugin.dataview.data.IDataViewRepo;
import com.sangmo.fts.basic.model.Company;
import com.sangmo.fts.basic.service.CompanyService;
import com.sangmo.fts.common.authority.service.AuthorityEntityService;
import com.sangmo.fts.process.inventory.interfaces.IfLoanCreation;
import com.sangmo.fts.process.inventory.model.IfLoan;
import com.sangmo.fts.process.inventory.model.IfStock;
import com.sangmo.fts.process.inventory.model.IfWaybill;
import com.sangmo.fts.process.inventory.repo.IfLoanRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;

@Service
@Transactional
public class IfLoanEntityService extends AuthorityEntityService<IfLoan> {

    @Autowired
    private IfLoanRepo ifLoanRepo;

    @Autowired
    private IdentityManager identityManager;

    @Autowired
    private IfWaybillService ifWaybillService;

    @Autowired
    private IfStockService ifStockService;

    @Autowired
    private CompanyService companyService;

    @Override
    protected IDataViewRepo<IfLoan> getRepo() {
        return ifLoanRepo;
    }


    @Override
    protected void onCreate(IfLoan entity, Object bo) {
        super.onCreate(entity, bo);
        IfLoanCreation creation = (IfLoanCreation) bo;
        entity.setApplyCode(DateUtils.format(new Date(), "yyyyMMdd") + identityManager.next("IF_LOAN", 5));
        IfWaybill waybill = ifWaybillService.get(creation.getWaybillId());
        IfStock stock = ifStockService.findByWaybillId(waybill.getId());
        Company company = companyService.get(creation.getApplyId());
        BigDecimal rate = calcRate(company, creation.getDuration());
        entity.setRate(rate);
        entity.setContractId(waybill.getContractId());
        entity.setStockId(stock.getId());
        entity.setBankId(company.getBankId());
        entity.setGoodsTotalAmount(stock.getGoodsTotalAmount());
    }

    private BigDecimal calcRate(Company company, String duration) {
        if (Company.CreditRating.D.equals(company.getCreditRating())) {
            throw new ServiceException(StandardErrors.CLIENT_ERROR.getStatus(), "error.company.creditRating.notEnough");
        }
        return Company.rateMap.get(company.getCreditRating()+"-"+duration);
    }
}
